package com.zjsru.oneday202208;


import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Author: likew
 * @Date: 2022/8/21
 * 检查单词是否为句中其他单词的前缀
 * 输入：sentence = "i love eating burger", searchWord = "burg"
 * 输出：4
 * 解释："burg" 是 "burger" 的前缀，而 "burger" 是句子中第 4 个单词。
 *
 * 输入：sentence = "this problem is an easy problem", searchWord = "pro"
 * 输出：2
 * 解释："pro" 是 "problem" 的前缀，而 "problem" 是句子中第 2 个也是第 6 个单词，但是应该返回最小下标 2 。
 *
 */
public class IsPrefixOfWord {
    public int isPrefixOfWord(String sentence, String searchWord) {
        String[] split = sentence.split(" ");
        List<Integer> ansList = new ArrayList<>();
        for (int i = 0; i < split.length; i++) {
            if (this.check(split[i], searchWord)) {
                ansList.add(i);
            }
        }
        if(ansList.size() > 0){
            return ansList.get(0) + 1;
        }else{
            return -1;
        }
    }
    
    /**
     * 检查前缀是否相同
     * */
    private boolean check(String s, String searchWord) {
        char[] cs = s.toCharArray();
        char[] chars = searchWord.toCharArray();
        for (int i = 0; i <= chars.length - 1; i++) {
            if(!Objects.equals(cs[i], chars[i]) || cs.length < chars.length){
                return false;
            }
        }
        return true;
    }
    
    public static void main(String[] args) {
        IsPrefixOfWord isPrefixOfWord = new IsPrefixOfWord();
        String sentence = "i love eating burger";
        String searchWord = "burg";
        System.out.println(isPrefixOfWord.isPrefixOfWord(sentence, searchWord));
    }
}
